//
//  userAccountViewModel.swift
//  Weibo
//
//  Created by 孙成宇 on 15/11/28.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit

import AFNetworking

class userAccountViewModel: NSObject {
    
    var account : UserAccount?
    
    
    override init() {
        super.init()
        
        account = UserAccount.loadAccount()
    }
    
    var uesrLogin: Bool {
    
       return account?.access_token != nil
        
    
    }
    var token : String?{
    
    
    return account?.access_token
    }
    
    var userName: String?{
    
    return account?.name
    
    }
    //用户头像 url
    var headImageURL: NSURL? {
        let url = NSURL(string: account?.avatar_large ?? "")
        return url
    }
    
    
    ////请求用户toKen
    func loadAccesssToken(code : String , finished:(error : NSError?)->()) {
        
        let urlString = "oauth2/access_token"
        
        let paramters = ["client_id":client_id,"client_secret":client_secret,"grant_type":"authorization_code","code":code,"redirect_uri":redirect_uri]
        NetworkTools.sharedTools.requestJSONDict(.POST, urlString: urlString, parameters: paramters) { (result, error) -> () in


            if error != nil {
        finished(error: error)
                       return
                
            }
            
            let account = UserAccount(dict: result!)
            
            self.loadUserInfo(account,finished: finished)
            
            

        }
    }
    
    
    private func loadUserInfo(account : UserAccount,finished:(error: NSError?)->()) {
        
        let urlString = "2/users/show.json"
        
        guard let access_token = account.access_token,userId = account.uid else{
           
            return
            
        }
        
        let parameters = ["access_token": access_token, "uid":userId]
        NetworkTools.sharedTools.requestJSONDict(.GET, urlString: urlString, parameters: parameters) { (result, error) -> () in

            if error != nil{

finished(error: error)
return
            }
        

            
            account.avatar_large = result!["avatar_large"] as? String
            
            account.name = result!["name"] as? String
            
            print(account)
            
            account.saveAccount()
            
            finished(error: nil)
            
        
            
           
        }
        
        
    }


}
